package org.jeecg.modules.demo.applet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.applet.mapper.AppletMapper;
import org.jeecg.modules.demo.applet.service.IAppletService;
import org.jeecg.modules.demo.basememberproject.service.IBaseMemberProjectService;
import org.jeecg.modules.demo.basememberprojectserve.service.IBaseMemberProjectServeService;
import org.jeecg.modules.demo.basememberprojectshop.service.IBaseMemberProjectShopService;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.baseorde.entity.BaseOrder;
import org.jeecg.modules.demo.baseorde.service.IBaseOrderService;
import org.jeecg.modules.demo.basepaydetail.entity.BasePayDetail;
import org.jeecg.modules.demo.basepaydetail.service.IBasePayDetailService;
import org.jeecg.modules.demo.basepayshop.service.IBasePayShopService;
import org.jeecg.modules.demo.basestaffshareholder.entity.BaseStaffShareholder;
import org.jeecg.modules.demo.basestaffshareholder.service.IBaseStaffShareholderService;
import org.jeecg.modules.demo.cashier.mapper.CashierMapper;
import org.jeecg.modules.demo.cashier.service.CashierService;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.shareholderrecord.service.IShareholderRecordService;
import org.jeecg.modules.demo.shopcommoditycart.service.IShopCommodityCartService;
import org.jeecg.modules.demo.shopprojectcart.service.IShopProjectCartService;
import org.jeecg.modules.demo.stockequitydetail.service.IStockEquityDetailService;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.totaldividendamount.service.ITotalDividendAmountService;
import org.jeecg.modules.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings("unchecked")
public class IAppletServiceImpl extends ServiceImpl<AppletMapper, Map<String, Object>> implements IAppletService {
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private IMemberManagementService memberManagementService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private IBaseOrderService baseOrderService;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IBasePayShopService basePayShopService;
    @Autowired
    private IBaseMemberProjectService baseMemberProjectService;
    @Resource
    private CashierMapper cashierMapper;
    @Autowired
    private CashierService cashierService;

    @Autowired
    private IBaseMemberProjectServeService baseMemberProjectServeService;
    @Autowired
    private IBaseMemberProjectShopService baseMemberProjectShopService;
    @Autowired
    private IBasePayDetailService basePayDetailService;
    @Autowired
    private IBaseStaffShareholderService baseStaffShareholderService;
    @Autowired
    private IStockEquityDetailService stockEquityDetailService;
    @Autowired
    private IShareholderRecordService shareholderRecordService;
    @Autowired
    private ITotalDividendAmountService totalDividendAmountService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private IShopCommodityCartService shopCommodityCartService;
    @Autowired
    private IShopProjectCartService shopProjectCartService;

    @Override
    public Result<?> getPreSaveOrder(Map<String, Object> map) {
//        String storeId = map.get("storeId") == null ? null : String.valueOf(map.get("storeId"));
//        String memberId = map.get("memberId") == null ? null : String.valueOf(map.get("memberId"));
//        String useMemberDiscountStr = map.get("useMemberDiscount") == null ? null : String.valueOf(map.get("useMemberDiscount"));
//        boolean useMemberDiscount = "1".equals(useMemberDiscountStr);
//        String memberDiscountStr = map.get("memberDiscount") == null ? null : String.valueOf(map.get("memberDiscount"));
//        BigDecimal memberDiscount = memberDiscountStr == null ? null : new BigDecimal(memberDiscountStr);
//        List<Map<String, Object>> commodityList = (List<Map<String, Object>>) map.get("commodityList");
//        List<String> couponIds = (List<String>) map.get("couponIds");
//        String remark = map.get("remark") == null ? null : String.valueOf(map.get("remark"));
//        String orderId = map.get("orderId") == null ? null : String.valueOf(map.get("orderId"));
//        String totalAmount = map.get("totalAmount") == null ? "0" : String.valueOf(map.get("totalAmount"));
//        String totalDiscountAmount = map.get("totalDiscountAmount") == null ? "0" : String.valueOf(map.get("totalDiscountAmount"));
//        String realAmount = map.get("realAmount") == null ? "0" : String.valueOf(map.get("realAmount"));
//        String patternPayment = map.get("patternPayment") == null ? "" : String.valueOf(map.get("patternPayment"));
//        String balanceAmountStr = map.get("balanceAmount ") == null ? null : String.valueOf(map.get("balanceAmount "));
//        String stockBalanceAmountStr = map.get("stockBalanceAmount") == null ? null : String.valueOf(map.get("stockBalanceAmount"));
//        //店铺数据
//        StoreInfo storeInfo = storeInfoService.getById(storeId);
//        //会员数据
//        MemberManagement mm = memberManagementService.getById(memberId);
//        if(mm == null){
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回退
//            return Result.error("获取会员信息异常");
//        }
//        // 关联的股东信息
//        StockManage sm = stockManageService.getById(mm.getStockId());
//        //股东会员 对应股东数据
//        QueryWrapper<StockManage> query = new QueryWrapper<>();
//        query.eq("member_id", mm.getId());
//        StockManage smm = stockManageService.getOne(query);
//
//        // ------------------------- 订单 -------------------------
//        BaseOrder order;
//        if(StringUtils.isNotEmpty(orderId)){
//            order = baseOrderService.getById(orderId);
//        } else {
//            order = new BaseOrder();
//            order.setOrderCode(ToolsUtils.getBillNo("LO"));//订单编号
//            baseOrderService.save(order);
//        }
//
//        order.setStoreId(storeId);//关联店铺
//        // 01 待付款 02 已付款 03 未自提 04  已自提 05  已完成  06  退款中 07  已退款
//        order.setOrderStatus("01");
//        // 1.店内订单 2.线上订单
//        order.setOrderType("02");
//        order.setCreateTime(new Date());
//        order.setShop(storeInfo.getStoreName());//所属门店
//        order.setRemark(remark);//买家留言
//        order.setCouponIds(JSON.toJSONString(couponIds));//使用的优惠劵列表
//        order.setReduction("0");//手动优惠金额
//        order.setStaffId(mm.getId());//操作人ID
//        order.setStaffName(mm.getName());//操作人
//        order.setStaffPhone(mm.getPhone());//操作人手机号
//        order.setMemberId(memberId);//会员ID
//        order.setMemberName(mm.getName());//会员姓名
//        order.setMemberPhone(mm.getPhone());//会员手机号
//        order.setMemberLevel(mm.getMemberLevel());//会员等级
//        if (sm != null) {
//            order.setStockId(sm.getId());
//            order.setStockName(sm.getStockName());//股东金额
//            order.setStockPhone(sm.getTel());//股东手机号
//        }
//        // 计算金额
//        order.setTotalAmount(new BigDecimal(totalAmount));
//        order.setTotalDiscountAmount(new BigDecimal(totalDiscountAmount));
//        order.setRealityAmount(realAmount);
//        order.setPatternPayment(ToolsUtils.getPatternPayment(patternPayment));
//        baseOrderService.updateById(order);
//
//        StringBuilder orderName = new StringBuilder();
//        commodityList.forEach(m -> {
//            String id = m.get("id") == null ? null : String.valueOf(m.get("id"));
//            String type = m.get("type") == null ? null : String.valueOf(m.get("type"));
//            String countStr = m.get("count") == null ? "0" : String.valueOf(m.get("count"));
//            BigDecimal count = new BigDecimal(countStr);
//            int countNum = Integer.parseInt(countStr);
//            String totalPrice = m.get("totalPrice") == null ? null : String.valueOf(m.get("totalPrice"));
//            String discountAmount = m.get("discountAmount") == null ? null : String.valueOf(m.get("discountAmount"));
//
//            if ("1".equals(type)) {
//                // ------------------------- 商品 -------------------------
//                CommodityManagement commodity = commodityManagementService.getById(id);
//                BasePayShop commodityC = new BasePayShop();
//                if (commodity == null) {
//                    commodityC = basePayShopService.getById(id);
//                    commodity = commodityManagementService.getById(commodityC.getShopId());
//                } else {
//                    BeanUtils.copyProperties(commodity, commodityC);
//                    commodityC.setId(null);
//                    basePayShopService.save(commodityC);
//                }
//
//                if (null != commodity) {
//                    commodityC.setShopId(commodity.getId());
//                    //cashierService.setUpdataInventory(commodity, countNum,storeId);
//                }
//
//                commodityC.setOrderId(order.getId());
//                commodityC.setNum(countNum);
//                commodityC.setOrderStatus("02");
//                commodityC.setMemberId(memberId);
//                basePayShopService.updateById(commodityC);
//
//                //setBasePayDetail(m, order, memberId, commodity, null);
//
//                // 拼接订单名
//                orderName.append(commodityC.getTradeName()).append(",");
//
//                // 处理购物车中的商品
//                ShopCommodityCart scc = shopCommodityCartService.getOne(new QueryWrapper<ShopCommodityCart>()
//                        .eq("member_id", memberId)
//                        .eq("commodity_id", id));
//                if (scc != null) {
//                    // 购物车里有该会员对该商品的收藏记录
//                    if (count.intValue() >= scc.getQty()) {
//                        // 购买数量大于等于收藏数量，则删除该收藏记录
//                        shopCommodityCartService.removeById(scc.getId());
//                    } else {
//                        // 购买数量小于收藏数量，则购物车收藏个数减去购买个数
//                        scc.setQty(scc.getQty() - count.intValue());
//                        shopCommodityCartService.updateById(scc);
//                    }
//                }
//            } else {
//                // ------------------------- 项目 -------------------------
//                ProjectManagement project = projectManagementService.getById(id);
//                BaseMemberProject projectC = new BaseMemberProject();
//                if (project == null) {
//                    projectC = baseMemberProjectService.getById(id);
//                    project = projectManagementService.getById(projectC.getProjectId());
//                } else {
//                    BeanUtils.copyProperties(project, projectC);
//                    projectC.setId(null);
//                    baseMemberProjectService.save(projectC);
//                }
//                if (project != null) {
//                    projectC.setProjectId(project.getId());
//                }
//
//                projectC.setOrderId(order.getId());
//                projectC.setNum(Integer.valueOf(countStr));
//                projectC.setOrderStatus("02");
//                projectC.setMemberId(memberId);
//                projectC.setTotalPrice(ToolsUtils.getNumerics(totalPrice));//总价
//                projectC.setPreferAmount(ToolsUtils.getNumerics(discountAmount));//优惠金额
//                projectC.setGiveFlag(0);//是否赠送（是：1，否：0）
//                baseMemberProjectService.updateById(projectC);
//
//                //setBasePayDetail(m, order, memberId, null, project);
//
//                // 拼接订单名
//                orderName.append(projectC.getProjectName()).append(",");
//
//                // 处理购物车中的项目
//                ShopProjectCart spc = shopProjectCartService.getOne(new QueryWrapper<ShopProjectCart>()
//                        .eq("member_id", memberId)
//                        .eq("commodity_id", id));
//                if (spc != null) {
//                    // 购物车里有该会员对该项目的收藏记录
//                    if (count.intValue() >= spc.getQty()) {
//                        // 购买数量大于等于收藏数量，则删除该收藏记录
//                        shopProjectCartService.removeById(spc.getId());
//                    } else {
//                        // 购买数量小于收藏数量，则购物车收藏个数减去购买个数
//                        spc.setQty(spc.getQty() - count.intValue());
//                        shopProjectCartService.updateById(spc);
//                    }
//                }
//            }
//        });
//        order.setJsonStr(JSON.toJSONString(map));
//
//        if (orderName.length() > 0) {
//            orderName.deleteCharAt(orderName.length() - 1);
//        }
//        order.setName(orderName.toString());
//        order.setBuyer(mm.getName());
//        baseOrderService.updateById(order);
//        return Result.OK(order);
        return Result.OK();
    }

    @Override
    public Result<?> saveOrder(Map<String, Object> map) {
//        String storeId = map.get("storeId") == null ? null : String.valueOf(map.get("storeId"));
//        String memberId = map.get("memberId") == null ? null : String.valueOf(map.get("memberId"));
//        String useMemberDiscountStr = map.get("useMemberDiscount") == null ? null : String.valueOf(map.get("useMemberDiscount"));
//        boolean useMemberDiscount = "1".equals(useMemberDiscountStr);
//        String memberDiscountStr = map.get("memberDiscount") == null ? null : String.valueOf(map.get("memberDiscount"));
//        BigDecimal memberDiscount = memberDiscountStr == null ? null : new BigDecimal(memberDiscountStr);
//        List<Map<String, Object>> commodityList = (List<Map<String, Object>>) map.get("commodityList");
//        List<String> couponIds = (List<String>) map.get("couponIds");
//        String remark = map.get("remark") == null ? null : String.valueOf(map.get("remark"));
//        String orderId = map.get("orderId") == null ? null : String.valueOf(map.get("orderId"));
//        String totalAmount = map.get("totalAmount") == null ? "0" : String.valueOf(map.get("totalAmount"));
//        String totalDiscountAmount = map.get("totalDiscountAmount") == null ? "0" : String.valueOf(map.get("totalDiscountAmount"));
//        String realAmount = map.get("realAmount") == null ? "0" : String.valueOf(map.get("realAmount"));
//        String patternPayment = map.get("patternPayment") == null ? "" : String.valueOf(map.get("patternPayment"));
//        String balanceAmountStr = map.get("balanceAmount ") == null ? null : String.valueOf(map.get("balanceAmount "));
//        String stockBalanceAmountStr = map.get("stockBalanceAmount") == null ? null : String.valueOf(map.get("stockBalanceAmount"));
//        String payCode = map.get("payCode") == null ? null : String.valueOf(map.get("payCode"));
//        //店铺数据
//        StoreInfo storeInfo = storeInfoService.getById(storeId);
//        //会员数据
//        MemberManagement mm = memberManagementService.getById(memberId);
//        if(mm == null){
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回退
//            return Result.error("获取会员信息异常");
//        }
//        // 关联的股东信息
//        StockManage sm = stockManageService.getById(mm.getStockId());
//        //股东会员 对应股东数据
//        QueryWrapper<StockManage> query = new QueryWrapper<>();
//        query.eq("member_id", mm.getId());
//        StockManage smm = stockManageService.getOne(query);
//
//        // ------------------------- 订单 -------------------------
//        BaseOrder order;
//        if(StringUtils.isNotEmpty(orderId)){
//            order = baseOrderService.getById(orderId);
//        } else {
//            order = new BaseOrder();
//            order.setOrderCode(ToolsUtils.getBillNo("LO"));//订单编号
//            baseOrderService.save(order);
//        }
//
//        order.setStoreId(storeId);//关联店铺
//        // 01 待付款 02 已付款 03 未自提 04  已自提 05  已完成  06  退款中 07  已退款
//        order.setOrderStatus("03");
//        // 1.店内订单 2.线上订单
//        order.setOrderType("02");
//        order.setPayCode(payCode);
//        order.setCreateTime(new Date());
//        order.setShop(storeInfo.getStoreName());//所属门店
//        order.setRemark(remark);//买家留言
//        order.setCouponIds(JSON.toJSONString(couponIds));//使用的优惠劵列表
//        order.setReduction("0");//手动优惠金额
//        order.setStaffId(mm.getId());//操作人ID
//        order.setStaffName(mm.getName());//操作人
//        order.setStaffPhone(mm.getPhone());//操作人手机号
//        order.setMemberId(memberId);//会员ID
//        order.setMemberName(mm.getName());//会员姓名
//        order.setMemberPhone(mm.getPhone());//会员手机号
//        order.setMemberLevel(mm.getMemberLevel());//会员等级
//        if (sm != null) {
//            order.setStockId(sm.getId());
//            order.setStockName(sm.getStockName());//股东金额
//            order.setStockPhone(sm.getTel());//股东手机号
//        }
//        // 计算金额
//        order.setTotalAmount(new BigDecimal(totalAmount));
//        order.setTotalDiscountAmount(new BigDecimal(totalDiscountAmount));
//        order.setRealityAmount(realAmount);
//        order.setPatternPayment(ToolsUtils.getPatternPayment(patternPayment));
//        baseOrderService.updateById(order);
//
//        AtomicReference<StringBuffer> orderName = new AtomicReference<>(new StringBuffer());
//        commodityList.forEach(m -> {
//            String id = m.get("id") == null ? null : String.valueOf(m.get("id"));
//            String type = m.get("type") == null ? null : String.valueOf(m.get("type"));
//            String countStr = m.get("count") == null ? "0" : String.valueOf(m.get("count"));
//            BigDecimal count = new BigDecimal(countStr);
//            int countNum = Integer.parseInt(countStr);
//            String totalPrice = m.get("totalPrice") == null ? null : String.valueOf(m.get("totalPrice"));
//            String discountAmount = m.get("discountAmount") == null ? null : String.valueOf(m.get("discountAmount"));
//
//            if ("1".equals(type)) {
//                // ------------------------- 商品 -------------------------
//                CommodityManagement commodity = commodityManagementService.getById(id);
//                BasePayShop commodityC = new BasePayShop();
//                if (commodity == null) {
//                    commodityC = basePayShopService.getById(id);
//                    commodity = commodityManagementService.getById(commodityC.getShopId());
//                } else {
//                    BeanUtils.copyProperties(commodity, commodityC);
//                    commodityC.setId(null);
//                    basePayShopService.save(commodityC);
//                }
//
//                if (null != commodity) {
//                    commodityC.setShopId(commodity.getId());
////                    cashierService.setUpdataInventory(commodity, countNum,storeId,mm.getName());
//                }
//
//                commodityC.setOrderId(order.getId());
//                commodityC.setNum(countNum);
//                commodityC.setOrderStatus("02");
//                //commodityC.setFree(freeStr);
//                //commodityC.setStaffId(staffId);
//                //commodityC.setStaffPercentage(staffPercentage);
//                commodityC.setMemberId(memberId);
//                basePayShopService.updateById(commodityC);
////                cashierService.setBasePayDetail(m, order, memberId, commodity, null);
//
//                if (orderName.get().length() > 0) orderName.get().append(",");
//                    orderName.get().append(commodityC.getTradeName());
//            } else {
//                // ------------------------- 项目 -------------------------
//                ProjectManagement project = projectManagementService.getById(id);
//                BaseMemberProject projectC = new BaseMemberProject();
//                if (project == null) {
//                    projectC = baseMemberProjectService.getById(id);
//                    project = projectManagementService.getById(projectC.getProjectId());
//                } else {
//                    BeanUtils.copyProperties(project, projectC);
//                    projectC.setId(null);
//                    baseMemberProjectService.save(projectC);
//                }
//                if (project != null) {
//                    projectC.setProjectId(project.getId());
//                }
//
//                projectC.setOrderId(order.getId());
//                projectC.setNum(Integer.valueOf(countStr));
//                projectC.setOrderStatus("02");
//                //projectC.setFree(freeStr);
//                //projectC.setStaffId(staffId);
//                //projectC.setStaffPercentage(staffPercentage);
//                projectC.setMemberId(memberId);
//                projectC.setTotalPrice(ToolsUtils.getNumerics(totalPrice));//总价
//                projectC.setPreferAmount(ToolsUtils.getNumerics(discountAmount));//优惠金额
//                projectC.setGiveFlag(0);//是否赠送（是：1，否：0）
//                baseMemberProjectService.updateById(projectC);
//
//                // 项目关联的商品：一个商品一条记录
//                List<Map<String, Object>> shopList = cashierMapper.listProjectShop(project != null ? project.getId() : "");
//                BaseMemberProject finalProjectC = projectC;
//                shopList.forEach(map1 -> {
//                    String countShopStr = map1.get("count") == null ? "0" : String.valueOf(map1.get("count"));
//                    // 一个项目包含几个商品
//                    BigDecimal countShop = new BigDecimal(countShopStr);
//                    CommodityManagement shop = ToolsUtils.mapToObject(map1, CommodityManagement.class);
//                    shop.setTradeName(map1.get("trade_name").toString());
//                    BaseMemberProjectShop shopC = new BaseMemberProjectShop();
//                    BeanUtils.copyProperties(shop, shopC);
//                    shopC.setMemberProjectId(finalProjectC.getId());
//                    shopC.setIsCancel("0");
//                    int i = countShop.multiply(count).intValue();
//                    for (int j = 0; j < i; j++) {
//                        shopC.setId(null);
//                        baseMemberProjectShopService.save(shopC);
//                    }
//                });
//
//                // 项目关联的服务：有多少次服务，就插入多少条记录
//                List<Map<String, Object>> serveList = cashierMapper.listProjectServe(project != null ? project.getId() : "");
//                serveList.forEach(map1 -> {
//                    String countServeStr = map1.get("count") == null ? "0" : String.valueOf(map1.get("count"));
//                    // 一个项目包含几个商品
//                    BigDecimal countServe = new BigDecimal(countServeStr);
//                    BaseJobServe serve = ToolsUtils.mapToObject(map1, BaseJobServe.class);
//                    serve.setServeName(map1.get("serve_name").toString());
//                    BaseMemberProjectServe serveC = new BaseMemberProjectServe();
//                    BeanUtils.copyProperties(serve, serveC);
//                    serveC.setId(null);
//                    serveC.setMemberProjectId(finalProjectC.getId());
//                    // 是否已核销（0.否 1.是）
//                    serveC.setIsCancel("0");
//                    int i = countServe.multiply(count).intValue();
//                    for (int j = 0; j < i; j++) {
//                        serveC.setId(null);
//                        baseMemberProjectServeService.save(serveC);
//                    }
//                });
//
////                cashierService.setBasePayDetail(m, order, memberId, null, project);
//
//                if (orderName.get().length() > 0) orderName.get().append(",");
//                    orderName.get().append(projectC.getProjectName());
//            }
//        });
//        order.setJsonStr(JSON.toJSONString(map));
//
//
//        double stockMoney = 0;
//        // 01=扫码支付（暂不支持） 02=现金支付 03=微信记账 04=支付宝记账 05=会员余额支付 06=股本余额支付
//        if (patternPayment.equals("01")) {
//            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回退
//            //return Result.error("暂不支持的支付模式");
//        }
//        if (patternPayment.equals("02")) {
//            order.setChargeAmount(new BigDecimal(realAmount));
//        }
//        if (patternPayment.equals("03")) {//微信记账
//            order.setWeixinAccount(new BigDecimal(realAmount));
//        }
//        if (patternPayment.equals("04")) {//支付宝记账
//            order.setZhifubaoAccount(new BigDecimal(realAmount));
//        }
//        if (patternPayment.equals("05")) {//会员余额支付
//            double reality = ToolsUtils.getNumerics(realAmount);
//            order.setBalanceAmount(new BigDecimal(reality));
//            double balance = ToolsUtils.getNumerics(mm.getBalance());
//            mm.setBalance(balance - reality);
//            memberManagementService.updateById(mm);
//        }
//        if (patternPayment.equals("06")) {//股本余额支付
//            double reality = ToolsUtils.getNumerics(realAmount);
//            order.setStockBalanceAmount(new BigDecimal(reality));
//            if (smm != null && smm.getId() != null) {
//                double balance = smm.getEquityBalance();
//                double stockLowest = smm.getStockLowest();
//                if (balance - stockLowest - reality < 0) {
//                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    Result.error("股本余额不足");
//                }
//                stockMoney += reality;
//                smm.setEquityBalance(balance - reality);
//                stockManageService.updateById(smm);
//            }
//        }
//
//        //使用会员余额抵扣
//        double balanceAmount = ToolsUtils.getNumerics(balanceAmountStr);
//        if (balanceAmount > 0) {
//            order.setBalanceAmount(new BigDecimal(String.valueOf(balanceAmount)));
//            double balance = ToolsUtils.getNumerics(mm.getBalance());
//            mm.setBalance(balance - balanceAmount);
//            memberManagementService.updateById(mm);
//        }
//        //使用股本可用余额抵扣
//        double stockBalanceAmount = ToolsUtils.getNumerics(stockBalanceAmountStr);
//        if (stockBalanceAmount > 0) {
//            stockMoney += stockBalanceAmount;
//            order.setStockBalanceAmount(new BigDecimal(stockBalanceAmount));
//            if (smm != null && smm.getId() != null) {
//                double balance = smm.getEquityBalance();
//                smm.setEquityBalance(balance - stockBalanceAmount);
//                stockManageService.updateById(smm);
//            }
//        }
//
//        //股本余额变化表
//        if (stockMoney > 0) {
//            StockEquityDetail stockEquityDetail = new StockEquityDetail();
//            stockEquityDetail.setStoreId(storeId);
//            stockEquityDetail.setStockId(sm != null ? sm.getId() : "");
//            stockEquityDetail.setMemberId(memberId);
//            stockEquityDetail.setMemberName(mm.getName());
//            stockEquityDetail.setTradeType("02");
//            stockEquityDetail.setAmount(stockMoney);
//            stockEquityDetailService.save(stockEquityDetail);
//        }
//
//        // 优惠劵消耗
//        if (!useMemberDiscount && !couponIds.isEmpty()) {
//            couponIds.forEach(id -> {
//                BaseMemberVipCoupon coupon = baseMemberVipCouponService.getById(id);
//                if (coupon != null) {
//                    int num = ToolsUtils.getNumeric(coupon.getNum());
//                    if (num > 0) {
//                        num = num - 1;
//                        coupon.setNum(num);
//                        baseMemberVipCouponService.updateById(coupon);
//                        // TODO 更新优惠劵 消耗记录
//                    }
//                }
//            });
//        }
//
//
//        order.setName(orderName.toString());
//        order.setBuyer(mm.getName());
//        baseOrderService.updateById(order);
//        return Result.OK(order);
        return Result.OK();
    }

    /**
     * 提成算法
     * 50 count 2  100 员工提成 0.2*100 = 20
     * 会员给股东提成   （实际售价 * 毛利率 * 股东分红比例 = 股东分红）
     * 价格 * 最低利率限额 = 老板最低获利
     * 老板最低获利 >= 实际售价 - 股东分红
     */
    public void setBasePayDetail(Map<String, Object> m, BaseOrder order, String memberId, CommodityManagement commodity, ProjectManagement project) {
        String id = m.get("id") == null ? "" : String.valueOf(m.get("id"));
        String type = m.get("type") == null ? "" : String.valueOf(m.get("type"));
        String discountAmountStr = m.get("discountAmount") == null ? "0" : String.valueOf(m.get("discountAmount"));
        String totalPriceStr = m.get("totalPrice") == null ? "0" : String.valueOf(m.get("totalPrice"));
        double amount = ToolsUtils.getNumerics(totalPriceStr) - ToolsUtils.getNumerics(discountAmountStr);

        //商品实付价格
        if (amount <= 0) {
            log.info("商品优惠完 变成了0元");
            return;
        }

        BasePayDetail basePayDetail = new BasePayDetail();
        BigDecimal staffBonus = BigDecimal.ZERO;//员工分红（股东管家分红）
        BigDecimal stockBonus = BigDecimal.ZERO;//股东分红
        int isStockBonus = 0;//是否给股东分红
        BigDecimal profit = BigDecimal.ZERO;//实际营收额（带动营业额度）
        BigDecimal saleroom = new BigDecimal(amount);//销售额
        double prorateDividends = 0;//股东分红比率
        double memberRatio = 0;//员工分股东的分红

        MemberManagement mm = memberManagementService.getById(memberId);
        StockManage sm = stockManageService.getById(mm.getStockId());
        String shareholdersHousekeeperId = "";
        if (sm != null) {
            basePayDetail.setStockId(sm.getId());
            prorateDividends = ToolsUtils.getScale(ToolsUtils.getNumerics(sm.getProrateDividends()) / 100);

            shareholdersHousekeeperId = sm.getShareholdersHousekeeperId();
            QueryWrapper<BaseStaffShareholder> query = new QueryWrapper<>();
            query.eq("staff_id", shareholdersHousekeeperId);//关联的管家分红
            query.eq("shareholder_id", sm.getId());
            BaseStaffShareholder baseStaffShareholder = baseStaffShareholderService.getOne(query);
            if (baseStaffShareholder != null) {
                memberRatio = ToolsUtils.getScale(ToolsUtils.getNumerics(baseStaffShareholder.getMemberRatio()) / 100);//给员工的分红比率
            }
        }

        //商品提成
        if (type.equals("1")) {
            double productPrice = ToolsUtils.getNumerics(commodity.getProductPrice());//价格
            double minimumMargin = ToolsUtils.getScale(ToolsUtils.getNumerics(commodity.getMinimumMargin()) / 100);//最低利率限额
            double grossRate = ToolsUtils.getScale(ToolsUtils.getNumerics(commodity.getGrossRate()) / 100);//毛利率
            double min = ToolsUtils.getScale(minimumMargin * productPrice);//老板最低获利
            double stockAward = ToolsUtils.getScale(amount * grossRate * prorateDividends);//股东分红
            double profits = amount - stockAward;
            if (min >= (profits)) {//给股东分红
                isStockBonus = 1;
                profit = new BigDecimal(String.valueOf(profits));
                if (memberRatio > 0 && memberRatio < 1) {
                    staffBonus = new BigDecimal(String.valueOf(stockAward * memberRatio));//员工分红（股东管家分红）
                    stockBonus = new BigDecimal(String.valueOf(stockAward - stockAward * memberRatio));//股东分红
                } else {
                    stockBonus = new BigDecimal(String.valueOf(stockAward));
                }
            } else {//不给股东分红
                isStockBonus = 0;
                profit = new BigDecimal(String.valueOf(amount));
            }
        }
        //项目提成
        if (type.equals("2")) {

            double productPrice = project.getProjectPrice();//价格
            double minimumMargin = ToolsUtils.getScale(ToolsUtils.getNumerics(project.getMinimumProfit()) / 100);//最低利率限额
            double grossRate = ToolsUtils.getScale(ToolsUtils.getNumerics(project.getGrossProfit()) / 100);//毛利率
            double min = ToolsUtils.getScale(minimumMargin * productPrice);//老板最低获利
            double stockAward = ToolsUtils.getScale(amount * grossRate * prorateDividends);//股东分红
            double profits = amount - stockAward;
            if (min >= (profits)) {//给股东分红
                isStockBonus = 1;
                profit = new BigDecimal(String.valueOf(profits));
                if (memberRatio > 0 && memberRatio < 1) {
                    staffBonus = new BigDecimal(String.valueOf(stockAward * memberRatio));//员工分红（股东管家分红）
                    stockBonus = new BigDecimal(String.valueOf(stockAward - stockAward * memberRatio));//股东分红
                } else {
                    stockBonus = new BigDecimal(String.valueOf(stockAward));
                }
            } else {//不给股东分红
                isStockBonus = 0;
                profit = new BigDecimal(String.valueOf(amount));
            }
        }

        basePayDetail.setSaleroom(saleroom);//销售额
        basePayDetail.setProfit(profit);//实际营收额（带动营业额度）
        basePayDetail.setStockBonus(stockBonus);//股东分红
        basePayDetail.setIsStockBonus(isStockBonus);//是否给股东分红
        basePayDetail.setStaffServeAward(BigDecimal.ZERO);
        basePayDetail.setType(type);//类型1=商品 2=项目
        basePayDetail.setOrderId(order.getId());
        basePayDetail.setMemberId(memberId);
        basePayDetail.setShopJobId(id);
//        basePayDetail.setStockId(order.getStockId());
        basePayDetail.setStoreId(order.getStoreId());
        basePayDetailService.save(basePayDetail);

        if (StringUtils.isNotEmpty(shareholdersHousekeeperId) && staffBonus.compareTo(BigDecimal.ZERO) > 0) {
            BasePayDetail basePayDetails = new BasePayDetail();
            basePayDetails.setStaffBonus(staffBonus);//员工分红（股东管家分红）
            basePayDetails.setStaffId(shareholdersHousekeeperId);
            basePayDetail.setOrderId(order.getId());
            basePayDetail.setType(type);//类型1=商品 2=项目
            basePayDetailService.save(basePayDetails);
        }

        //m.put("giftNum", staffShopAward.doubleValue() + staffProjectAward.doubleValue());
    }
}
